package org.esgl3d.rendering;

import java.nio.FloatBuffer;

import org.esgl3d.rendering.VertexContainer.BufferStructure;


/**
 * Acts as a wrapper for legacy opengl commands. Handles internal state
 * of color and texture coordinates.
 * 
 * @author michael
 *
 */
public class LegacyGLWrapper {
	FloatBuffer buffer;
	
	private float a;
	private float r;
	private float g;
	private float b;
	
	private float u;
	private float v;
	
	private VertexFormat type;
	private int number;
	private int numberOfVertices;
	private VertexContainer container;
	
	public LegacyGLWrapper(FloatBuffer setBuffer, VertexFormat format, VertexContainer setContainer) {
		buffer = setBuffer;
		type = format;
		numberOfVertices = setContainer.getNumberOfVertices();
		container = setContainer;
	}
	
	public void glBegin() {
		number = 0;
	}
	
	public void glVertex2f(float x, float y) {
		glVertex3f(x, y, 0);
	}
	
	public void glVertex3f(float x, float y, float z) {
		
		if (container.structure == BufferStructure.Stacked) {
			// write color parts
			if (type.components[VertexFormat.COLOR] > 0) {
				buffer.position(type.offsets[VertexFormat.COLOR]*numberOfVertices + number*type.components[VertexFormat.COLOR]);
				buffer.put(r);
				buffer.put(g);
				buffer.put(b);
				buffer.put(a);
			}
			
			// write texture parts
			if (type.components[VertexFormat.TEXTURE] > 0) {
				buffer.position(type.offsets[VertexFormat.TEXTURE]*numberOfVertices + number*type.components[VertexFormat.TEXTURE]);
				buffer.put(u);
				buffer.put(v);
			}
			
			// write vertex parts
			if (type.components[VertexFormat.POSITION] == 2) {
				buffer.position(type.offsets[VertexFormat.POSITION]*numberOfVertices + number*type.components[VertexFormat.POSITION]);
				buffer.put(x);
				buffer.put(y);
			} else if (type.components[VertexFormat.POSITION] == 3)  {
				buffer.position(type.offsets[VertexFormat.POSITION]*numberOfVertices + number*type.components[VertexFormat.POSITION]);
				buffer.put(x);
				buffer.put(y);
				buffer.put(z);
			}
		} else {
			buffer.position(type.totalFloats * number);
			// write color parts
			if (type.components[VertexFormat.COLOR] > 0) {
				buffer.put(r);
				buffer.put(g);
				buffer.put(b);
				buffer.put(a);
			}
			
			// write texture parts
			if (type.components[VertexFormat.TEXTURE] > 0) {
				buffer.put(u);
				buffer.put(v);
			}
			
			// write vertex parts
			if (type.components[VertexFormat.POSITION] == 2) {
				buffer.put(x);
				buffer.put(y);
			} else if (type.components[VertexFormat.POSITION] == 3)  {
				buffer.put(x);
				buffer.put(y);
				buffer.put(z);
			}
		}
		
		number ++;
	}
	
	public void glTexCoord2f(float u, float v) {
		this.u = u;
		this.v = v;
	}
	
	public void glColor4f(float r, float g, float b,float a) {
		this.a = a;
		this.r = r;
		this.g = g;
		this.b = b;
	}

	public void glEnd() {
		// does nothing
		
	}
}
